#include <fstream>
#include <vector>

#include "src/aot-compiler/aot.h"
#include "src/pbc/portable-logging.h"
#include "src/pbc/transform/portable-deserializer.h"

bool ends_with(const char* input, const char* suffix) {
  size_t input_length = strlen(input);
  size_t suffix_length = strlen(suffix);
  if (suffix_length <= input_length) {
    return strcmp(input + input_length - suffix_length, suffix) == 0;
  }
  return false;
}

void DumpPbc(const char* filename) {
  std::ifstream infile(filename, std::ifstream::binary);
  P_CHECK(infile.good());
  std::vector<uint8_t> buffer;
  infile.seekg(0, std::ifstream::end);
  size_t file_size = infile.tellg();
  infile.seekg(0);
  buffer.resize(file_size);
  infile.read(reinterpret_cast<char*>(buffer.data()), file_size);
  portable::PbcDeserializer deserializer;
  const portable::PbcScript* pbc_script =
      deserializer.Run(buffer.data(), static_cast<uint32_t>(buffer.size()));
  pbc_script->Dump();
}

int Main(int argc, char* argv[]) {
// TODO: support precompile_with_ir_new_be
#if 0
  bool debug = false;
  bool use_strict = false;
  for (int i = 0; i < argc; i++) {
    const char* arg = argv[i];
    if (!ends_with(arg, ".js")) {
      // TODO:(ck) add options dealing here
      if (strcmp(arg, "--no-use-copyable") == 0) {
        portable::enable_copyable = false;
      } else if (strcmp(arg, "--log-pbc") == 0) {
        debug = true;
      } else if (strcmp(arg, "--use-strict") == 0) {
        use_strict = true;
      }
      continue;
    }
    uintptr_t ret = portable::AOT::precompile_with_js(arg, debug, use_strict,
                                                      nullptr, true);
    if (ret == 0) {
      print("Compile '%s' Failed!\n", arg);
      return 1;
    }
  }
#endif
  return 0;
}

int main(int argc, char* argv[]) { return Main(argc, argv); }